import logging
import re
from utils.global_variable_tool import gv
from utils.common_var_tool import cv
from conf.settings import PATTERN
from utils.mysql_tool import MySQLDB  # 添加MySQLDB的导入
logger = logging.getLogger(__name__)

def var_substitution(param):
    '''常用变量占位符替换为实际值'''
    var_dic = cv.getCommonVar()
    logger.info("常用变量：{}".format(var_dic))

    for key in var_dic:
        if key in param:
            param = param.replace(key, str(var_dic[key]))  # replace返回替换后的新字符串
    return param

def parameter_substitution(param):
    '''依赖参数值替换为实际值'''
    keys = re.findall(PATTERN, param)
    print(keys)
    for key in keys:
        value = gv.getVar(key)
        param = param.replace('${' + key + '}', str(value))  # replace返回替换后的新字符串
    return param

def execute_init_sql(initSql):
    '''执行初始化SQL语句'''
    my = MySQLDB()  # 实例化数据库连接对象
    for sql in initSql:
        sql = var_substitution(sql)
        if sql.strip().startswith('select'):
            res = my.query(sql)
            logger.info("{}查询结果是：{}".format(sql, res))
        else:
            res = my.execute(sql)
            logger.info("操作成功：{}条".format(res))